local skynet = require "skynet"
local socket = require "skynet.socket"
local packet = require "packet"
local redis = require "redisutil"

local tunpack = table.unpack
local agent_pool

local function login(clientfd, name, password)
    if not name and not password then
        packet.send_packet(clientfd, "没有设置用户名或者密码")
        socket.close(clientfd)
        return
    end
    local client = {}
    local ok = redis:exists("role:"..name)
    if not ok then
        local score = 1000
        -- 满足条件唤醒协程，不满足条件挂起协程
        redis:hmset("role:"..name, tunpack({
            "name", name,
            "password", password,
            "score", score,
            "isgame", 0,
        }))
        client.fd = clientfd
        client.name = name
        client.password = password
        client.score = score
        client.isgame = 0
    else
        local dbs = redis:hgetall("role:"..name)
        if dbs.password ~= password then
            packet.send_packet(clientfd, "密码错误，请重新输入密码")
            return
        end
        client = dbs
        client.fd = clientfd
        client.isgame = tonumber(client.isgame) or 0
    end
    local addr = skynet.call(agent_pool, "lua", "fetch")
    if client.isgame > 0 then
        client.agent = addr
        ok = pcall(skynet.call, client.isgame, "lua", "online", client)
        if not ok then
            client.isgame = 0
            packet.send_packet(clientfd, "请准备开始游戏。。。")
        end
    else
        packet.send_packet(clientfd, "请准备开始游戏。。。")
    end
    skynet.call(addr, "lua", "start", client)
end

local function accept(clientfd, addr)
    -- skynet.newservice("agent", clientfd, addr)
    print("recv a connection:", clientfd, addr)
    socket.start(clientfd)
    local data = packet.recv_packet(clientfd)
    if not data then
        socket.close(clientfd)
        return
    end
    if data[1] ~= "login" then
        packet.send_packet(clientfd, "请先登录")
        socket.close(clientfd)
        return
    end
    socket.abandon(clientfd)
    login(clientfd, select(2, tunpack(data)))
end

skynet.start(function ()
    local listenfd = socket.listen("0.0.0.0", 8888)
    redis:init(skynet.uniqueservice("redis"))
    skynet.uniqueservice("hall")
    agent_pool = skynet.uniqueservice("agent_pool")
    skynet.call(agent_pool, "lua", "start")
    socket.start(listenfd, accept)
end)
